package com.zhang.webadmin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.webadmin.pojo.AclPermission;
import com.zhang.webadmin.pojo.AclRolePermission;
import com.zhang.webadmin.pojo.AclUser;
import com.zhang.webadmin.service.AclPermissionService;
import com.zhang.webadmin.service.AclRolePermissionService;
import com.zhang.webadmin.service.AclUserService;
import com.zhang.webadmin.util.CurrentLoginUserUtil;
import com.zhang.webadmin.util.R;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/aclpermission")
@Validated
public class AclPermissionController {
    @Resource
    private AclPermissionService aclPermissionService;
    @Resource
    private AclRolePermissionService aclRolePermissionService;

    @PreAuthorize("hasAuthority('aclpermission:query')")
    @GetMapping("/list")
    public R list(@RequestParam(required = false, defaultValue = "1") Integer page,
                  @RequestParam(required = false, defaultValue = "10") Integer size) {

        Page<AclPermission> dataPage = aclPermissionService.lambdaQuery()
                .orderByDesc(AclPermission::getCreateTime)
                .page(Page.of(page, size));

        return R.page(dataPage.getRecords(), dataPage.getTotal());
    }

    //    @PreAuthorize("hasAuthority('aclpermission:query')")
    @GetMapping("/tree")
    public R listTree() {
        List<AclPermission> permissionList = aclPermissionService.lambdaQuery()
                .list();
        List<AclPermission> rootMenuList = permissionList.stream().filter(item -> item.getParentId() == 0).toList();

        rootMenuList.forEach(item -> setChildren(permissionList, item));
        return R.ok(rootMenuList);
    }

    @GetMapping("/cascaderData")
    public R listCascader() {
        List<AclPermission> permissionList = aclPermissionService.lambdaQuery()
                .eq(AclPermission::getType, "menu")
                .list();
        List<AclPermission> rootMenuList = permissionList.stream().filter(item -> item.getParentId() == 0).toList();

        rootMenuList.forEach(item -> setChildren(permissionList, item));
        return R.ok(rootMenuList);
    }

    private void setChildren(List<AclPermission> permissionList, AclPermission parent) {
        List<AclPermission> children = permissionList.stream()
                .filter(item -> item.getParentId().equals(parent.getId()))
                .toList();
        if (!children.isEmpty()) {
            parent.setChildren(children);
            children.forEach(item -> setChildren(permissionList, item));
        }
    }

    @Resource
    private AclUserService aclUserService;

    // 获取用户有哪些menu和哪些button
    @GetMapping("/userPermission")
    public R userPermission() {
        AclUser aclUser = CurrentLoginUserUtil.curr();
        List<AclPermission> permissionList = aclUserService.queryPermission(aclUser.getId());
        List<AclPermission> rootMenuList = permissionList.stream().filter(item -> item.getParentId() == 0).toList();

        rootMenuList.forEach(item -> setChildren(permissionList, item));
        return R.ok(rootMenuList);
    }


    @PreAuthorize("hasAuthority('aclpermission:query')")
    @GetMapping("/{id}")
    public R getById(@NotNull(message = "id不能为空") @PathVariable Long id) {
        AclPermission aclPermission = aclPermissionService.getById(id);
        if (aclPermission == null) {
            return R.fail("不存在");
        }
        return R.ok(aclPermission);
    }

    //    @PreAuthorize("hasAuthority('aclpermission:add')")
    @PostMapping("/save")
    public R add(@Validated AclPermission aclPermission) {
        if (aclPermission.getId() != null) {
            return R.fail("不能传递ID值");
        }
        aclPermission.setCreateTime(LocalDateTime.now());
        aclPermission.setUpdateTime(LocalDateTime.now());

        aclPermissionService.save(aclPermission);

        return R.ok();
    }

    //    @PreAuthorize("hasAuthority('aclpermission:edit')")
    @PutMapping("/edit")
    public R edit(@Validated AclPermission aclPermission) {
        if (aclPermission.getId() == null) {
            return R.fail("传递ID值");
        }
        aclPermission.setUpdateTime(LocalDateTime.now());
        aclPermissionService.updateById(aclPermission);
        return R.ok();
    }

    //    @PreAuthorize("hasAuthority('aclpermission:delete')")
    @DeleteMapping("/{id}")
    public R delete(@NotNull(message = "id不能为空") @PathVariable Long id) {
        AclPermission aclPermission = aclPermissionService.getById(id);
        if (aclPermission == null) {
            return R.fail("不存在");
        }
        // 是否分配了
        Long count = aclRolePermissionService.lambdaQuery()
                .eq(AclRolePermission::getPermissionId, id)
                .count();
        if (count > 0) {
            return R.fail("菜单已经分配，无法删除");
        }
        aclPermissionService.removeById(id);
        return R.ok();
    }
}
